package top.malaoshi.netdisk.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 解决 使用 uni.download() 下载图片跨域的过滤器
 */
@WebFilter("/upload/*")
public class F0UploadFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String servletPath = req.getServletPath();
        String fileName = servletPath.substring(servletPath.lastIndexOf("/")+1);
//        resp.setHeader("Access-Control-Allow-Origin","*");
        String origin = req.getHeader("Origin");
        resp.setHeader("Access-Control-Allow-Origin",origin);
        resp.setHeader("Access-Control-Allow-Methods","GET");
        /*
        设置Access-Control-Expose-Headers暴露Content-Disposition响应头
        否则uniapp下载时要获取Content-Disposition，导致出现Refused to get unsafe header错误
         */
        resp.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        // 对文件名进行编码，对于标准英文名来说，没有任何变化
        String fileNameEncode = URLEncoder.encode(fileName, "UTF-8");
        resp.addHeader("Content-Disposition", "attachment;filename=" + fileNameEncode);

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
